#define _CRT_SECURE_NO_WARNINGS 1

#include"list.h"

ListNode* BuyList(LTDatatype x)
{
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		exit(-1);
	}

	newnode->x = x;
	newnode->next = NULL;
	newnode->prev = NULL;

	return newnode;
}

//void ListInit(ListNode** phead)
//{
//	*phead = BuyList(-1);
//	(*phead)->next = *phead;
//	(*phead)->prev = *phead;
//}

ListNode* ListInit()
{
	ListNode* phead = BuyList(-1);
	phead->next = phead;
	phead->prev = phead;
	return  phead;
}

void LTPushBack(ListNode* phead, LTDatatype x)
{
	ListNode* newnode = BuyList(x);
	ListNode* tail = phead->prev;

	tail->next = newnode;
	newnode->prev = tail;
	newnode->prev = tail;
	newnode->next = phead;
	phead->prev = newnode;
}

void LTprint(ListNode* phead)
{
	ListNode* cur = phead->next;
	
	while (cur != phead)
	{
		printf("%d ", cur->x);
		cur = cur->next;
	}
	printf("\n");
}

void LTPushFront(ListNode* phead, LTDatatype x)
{
	ListNode* newnode = (ListNode*)BuyList(x);
	ListNode* head = phead->next;

	head->prev = newnode;
	newnode->prev = phead;
	newnode->next = head;
	phead->next = newnode;
}

void LTPopBack(ListNode* phead)
{
	assert(phead);
	assert(!LTempty(phead));

	ListNode* newtail = phead->prev->prev;
	free(phead->prev);

	newtail->next = phead;
	phead->prev = newtail;
}


void LTPopFront(ListNode* phead)
{
	assert(phead);
	assert(!LTempty(phead));

	ListNode* newhead = phead->next->next;
	free(phead->next);

	newhead->prev = phead;
	phead->next = newhead;
}

bool LTempty(ListNode* phead)
{
	assert(phead);

	return phead->next == phead;
}


ListNode* LTFind(ListNode* phead, LTDatatype x)
{
	assert(phead);

	ListNode* cur = phead;
	
	while (cur != cur->next)
	{
		if (cur->x == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}


void LTInsert(ListNode* pose, LTDatatype x)
{
	assert(pose);

	ListNode* Newnode = BuyList(x);
	ListNode* prev = pose->prev;

	prev->next = Newnode;
	Newnode->prev = prev;
	Newnode->next = pose;
	pose->prev = Newnode;
}

void LTErase(ListNode* pose)
{
	assert(pose);
	assert(!LTempty(pose));

	ListNode* prev = pose->prev;
	ListNode* next = pose->next;
	
	prev->next = next;
	next->prev = prev;
	free(pose);
}

void LTDestory(ListNode* head)
{
	assert(head);

	ListNode* cur = head;
	ListNode* next = head->next;

	while (next != cur)
	{
		free(cur);
		cur = next;
		next = next->next;
	}

	free(head);
}